package com.iphone.extra;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.widget.TextView;

import com.iphone.extra.view.IWidgetFrameLayout;
import com.iphone.extra.view.RoundImageView;
import com.iphone.extra.view.ShortcutWidgetLayout;

import java.io.File;

public class WidgetPhotoLayout extends IWidgetFrameLayout {

    private RoundImageView mPhotoView;

    private String mCurFilePath;
    private final ContentResolver mResolver;
    private final int PHOTO_SIZE = 320;

    public WidgetPhotoLayout(Context context) {
        this(context, null, 0);
    }

    public WidgetPhotoLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WidgetPhotoLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mResolver = context.getContentResolver();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mPhotoView = (RoundImageView) findViewById(R.id.photo_image_view);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        updatePhoto();
        mResolver.registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, mObserver);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mResolver.unregisterContentObserver(mObserver);
    }

    private final ContentObserver mObserver = new ContentObserver(getHandler()) {

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            postDelayed(new Runnable() {

                @Override
                public void run() {
                    updatePhoto();
                }
            }, 1000);
        }
    };

    private void updatePhoto() {
        String filePath = loadLatestImageFromGallery();
        if (filePath != null) {
            File file = new File(filePath);
            if (file.exists() && !filePath.equals(mCurFilePath)) {
                mCurFilePath = filePath;
                mPhotoView.setBitmap(getBitmapFromFile(file));
                mPhotoView.setVisibility(VISIBLE);
            }
        } else {
            mPhotoView.setVisibility(INVISIBLE);
        }
    }

    private Bitmap getBitmapFromFile(File file) {
        if (file != null && file.exists()) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
            options.inJustDecodeBounds = false;
            options.inSampleSize = options.outWidth / PHOTO_SIZE;
            return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
        }
        return null;
    }

    private String loadLatestImageFromGallery() {
        String imageName = null;
        Cursor cursor = null;
        try {
            cursor = getContext().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media.BUCKET_DISPLAY_NAME + "=? and " + MediaStore.Images.Media.MIME_TYPE + "=?", new String[]{"Camera", "image/jpeg"}, MediaStore.Images.Media.DATE_MODIFIED);
            if (cursor != null) {
                if (cursor.moveToLast()) {
                    imageName = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                }
            }
        } catch (Exception e) {
        } catch (Throwable t) {
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return imageName;
    }

    @Override
    public boolean onCellClicked(String describe) {
        try {
            Intent intent = new Intent();
            intent.setClassName("com.android.gallery3d", "com.android.gallery3d.app.GalleryActivity");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            getContext().startActivity(intent);
            getContext().sendBroadcast(new Intent(ShortcutWidgetLayout.ACTION));
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    @Override
    public String getLabel(Resources res) {
        return res.getString(R.string.widget_label_photo);
    }
}
